/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.csp.sentinel.slots.block.flow.controller;

import java.util.concurrent.atomic.AtomicLong;

import com.alibaba.csp.sentinel.slots.block.flow.TrafficShapingController;

import com.alibaba.csp.sentinel.util.TimeUtil;
import com.alibaba.csp.sentinel.node.Node;

/**
 * @author jialiang.linjl
 * 漏桶算法
 * 流控效果：排队等待
 */
public class RateLimiterController implements TrafficShapingController {

    private final int maxQueueingTimeMs;
    private final double count;

    private final AtomicLong latestPassedTime = new AtomicLong(-1);

    public RateLimiterController(int timeOut, double count) {
        this.maxQueueingTimeMs = timeOut;
        this.count = count;
    }

    @Override
    public boolean canPass(Node node, int acquireCount) {
        return canPass(node, acquireCount, false);
    }

    @Override
    public boolean canPass(Node node, int acquireCount, boolean prioritized) {
        // Pass when acquire count is less or equal than 0.
        if (acquireCount <= 0) {
            return true;
        }
        // Reject when count is less or equal than 0.
        // Otherwise,the costTime will be max of long and waitTime will overflow in some cases.
        if (count <= 0) {
            return false;
        }

        long currentTime = TimeUtil.currentTimeMillis();
        // Calculate the interval between every two requests.
        /**
         * 这里是根据当前请求的次数，通常都是1
         * 根据次数和当前设置的qps，计算两次请求之间的间隔，比如: 当前QPS是10，那两次请求的间隔就是100ms
         * count就是配置的阈值，比如：配置的QPS阈值是10
         */
        long costTime = Math.round(1.0 * (acquireCount) / count * 1000);

        // Expected pass time of this request. 理论上的间隔时间 + 上次请求通过的时间，就可以得到这次请求理论上的通过时间
        long expectedTime = costTime + latestPassedTime.get();

        /**
         * 如果满足下面的if 表示这次请求在100ms 之后，请求可以通过；然后设置最后通过时间为current
         *
         * 这里有一个问题，如果在110ms的时候，同时进来了100个请求，那这样都会进来
         */
        if (expectedTime <= currentTime) {
            // Contention may exist here, but it's okay.
            latestPassedTime.set(currentTime);
            return true;
        } else {
            // Calculate the time to wait.
            /**
             * 如果不满足，表示这次请求时间不满足间隔要求，就会等待相应的时间
             *  1、但是如果需要等待的时间，超过了配置的最长等待时间，就返回false，不通过
             *      比如：QPS设置为10，设置最长等待时间是50ms  在110ms的时候，第二次请求进来，此时会发现还有90ms才到第二次请求的时间，此时大于50ms，就会返回false
             *  2、如果要休眠的时间，小于最长等待时间，就会sleep，只是在sleep之前，再进行一次判断。如果此时已经到了执行间隔的时间，就返回true
             */
            long waitTime = costTime + latestPassedTime.get() - TimeUtil.currentTimeMillis();
            if (waitTime > maxQueueingTimeMs) {
                return false;
            } else {
                long oldTime = latestPassedTime.addAndGet(costTime);
                try {
                    waitTime = oldTime - TimeUtil.currentTimeMillis();
                    if (waitTime > maxQueueingTimeMs) {
                        latestPassedTime.addAndGet(-costTime);
                        return false;
                    }
                    // in race condition waitTime may <= 0
                    if (waitTime > 0) {
                        Thread.sleep(waitTime);
                    }
                    return true;
                } catch (InterruptedException e) {
                }
            }
        }
        return false;
    }

}
